const Koa = require('koa');
const Router = require('koa-router');
const koaStatic = require('koa-static');
const koaBody = require('koa-body');
const app = new Koa();
const router = new Router();
const fs = require('fs');
const path = require('path');

router.post('/api/upload',async (ctx)=>{
    const file = ctx.request.body.croppedImage; // base64 
    // 这里因为我上传的是一个base64编码的图片，所以这里用base来进行截取是可以的
    const imgType = file.match(/data:image\/(png|jpep|jpg|gif|webp);/)[1];
    const filename = `${+new Date()}_${Math.random()*100000000}.${imgType}`;
    const publicPath = `//${ctx.request.header.host}/upload_imgs/${filename}`;
    const filepath =  path.join(__dirname, `upload_imgs/${filename}`);
    const fileBuffer = Buffer.from(file.replace(/^data:image\/(png|jpep|jpg|gif|webp);base64,/, ""), 'base64'); //把base64码转成buffer对象，
    fs.writeFileSync(filepath, fileBuffer);
    ctx.body = JSON.stringify({
        code: 0,
        data: {
            path: publicPath,
        },
        message: 'success'
    });
});
app.use(koaStatic(__dirname));
app.use(koaBody({
    multipart: true,
    formidable: {
        maxFileSize: 1024*1024*1024    // 设置上传文件大小最大限制，默认2M
    }
}));
app.use(router.routes());
app.listen(8080, () => {
    console.log('请访问： http://localhost:8080/cutdemo.html');
});

// let fileRes = fs.readFileSync(path.join(__dirname, 'upload_imgs/123.png'), 'base64');
// fileRes = encodeURIComponent(fileRes);
// console.log(fileRes);

/**
 * 学习代码： 关于http2
 * const http2 = require('http2');
 * const http2Options = {
 *  key: fs.read
 *  cert: 
 * };
 * http2.createSecureServer(http2Options, app.callback()).listen(8080);
 */